import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
import { visualizer } from 'rollup-plugin-visualizer'

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  // Load env variables based on mode
  const env = loadEnv(mode, process.cwd())

  return {
    plugins: [
      react(),
      // 包分析插件，仅在analyze模式下启用
      mode === 'analyze' && visualizer({
        filename: 'dist/stats.html',
        open: true,
        gzipSize: true,
        brotliSize: true,
      }),
    ].filter(Boolean),
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
      },
    },
    server: {
      host: env.VITE_HOST || '0.0.0.0',
      port: parseInt(env.VITE_PORT || '3000'),
      open: env.VITE_OPEN !== 'false',
      // Use environment variables for allowed hosts
      allowedHosts: (env.VITE_ALLOWED_HOSTS || 'ai.olabstar.com,u.olabstar.com').split(','),
      proxy: {
        // WebSocket监控API代理到test-platform-service
        '/api': {
          target: env.VITE_API_TARGET || 'http://proxy-ui.cityark.cn/test-platform-service',
          changeOrigin: true,
          rewrite: (path) => path
        },
        '/langchain-backend': {
          target: env.VITE_LANGCHAIN_TARGET || 'http://proxy-ui.cityark.cn/langchain-backend/api',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/langchain-backend/, '')
        },
        // 聊天服务API代理到本地后端服务
        '/service': {
          target: env.VITE_SERVICE_TARGET || 'http://proxy-ui.cityark.cn/test-platform-service',
          changeOrigin: true,
        },
        // 代理WebSocket请求
        '/ws': {
          target: env.VITE_WS_TARGET || 'ws://proxy-ui.cityark.cn/test-platform-service',
          ws: true,
          changeOrigin: true,
        },
        '/kgflow/api/v1/': {
          target: env.VITE_KGFLOW_API_TARGET || 'http://kg-dev.olabstar.com:9380/',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/kgflow/, ''),
          headers: {
            'Authorization': env.VITE_KGFLOW_AUTH || 'Bearer ragflow-I3YWJiYzcyNTcxMDExZjBiMmNmOTYxZT',
            'Content-Type': 'application/json'
          }
        },
        '/kgflow/v1/agents/': {
          target: env.VITE_KGFLOW_AGENTS_TARGET || 'http://kg-dev.olabstar.com:9380/',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/kgflow/, ''),
          headers: {
            'Authorization': env.VITE_KGFLOW_AUTH || 'Bearer ragflow-I3YWJiYzcyNTcxMDExZjBiMmNmOTYxZT',
            'Content-Type': 'application/json'
          }
        },
        '/kgflow/api/knowledge/master/': {
          target: env.VITE_LANGCHAIN_TARGET || 'http://proxy-ui.cityark.cn/langchain-backend/api',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/kgflow/, ''),
          headers: {
            'Authorization': env.VITE_KGFLOW_AUTH || 'Bearer ragflow-I3YWJiYzcyNTcxMDExZjBiMmNmOTYxZT',
            'Content-Type': 'application/json'
          }
        }
      },
    },
    build: {
      outDir: 'dist',
      sourcemap: false, // 生产环境关闭sourcemap
      minify: 'terser', // 使用terser进行更好的压缩
      chunkSizeWarningLimit: 1000, // 调整chunk大小警告阈值
      terserOptions: {
        compress: {
          drop_console: true, // 移除console.log
          drop_debugger: true, // 移除debugger
        },
      },
      rollupOptions: {
        output: {
          // 手动分块策略
          manualChunks: {
            // React相关库单独打包
            'react-vendor': ['react', 'react-dom', 'react-router-dom'],
            // Ant Design相关库单独打包
            'antd-vendor': ['antd', '@ant-design/icons', '@ant-design/charts'],
            // 工具库单独打包
            'utils-vendor': ['clsx', 'date-fns', 'dayjs'],
          },
          // 优化文件命名
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: (assetInfo) => {
            const info = assetInfo.name.split('.')
            const extType = info[info.length - 1]
            if (/\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/i.test(assetInfo.name)) {
              return `assets/media/[name]-[hash].${extType}`
            }
            if (/\.(png|jpe?g|gif|svg)(\?.*)?$/i.test(assetInfo.name)) {
              return `assets/images/[name]-[hash].${extType}`
            }
            if (/\.(woff2?|eot|ttf|otf)(\?.*)?$/i.test(assetInfo.name)) {
              return `assets/fonts/[name]-[hash].${extType}`
            }
            if (/\.(pdf)(\?.*)?$/i.test(assetInfo.name)) {
              return `assets/pdf/[name].[extname]`
            }
            return `assets/${extType}/[name]-[hash].${extType}`
          }
        }
      },
      // 启用gzip压缩
      reportCompressedSize: true,
      // 优化依赖预构建
      commonjsOptions: {
        include: [/node_modules/],
      },
    },
    // 优化依赖预构建
    optimizeDeps: {
      include: [
        'react',
        'react-dom',
        'react-router-dom',
        'antd',
        '@ant-design/icons',
        '@ant-design/charts',
        'clsx',
        'date-fns',
        'dayjs'
      ],
    },
  }
})
